-module(injectpcap).
-export([do/2,do/1,reader_cb/1,list_file/0]).
-record(frame_info,{version,interface,counter}).
list_file() ->
  {ok,File_List} = file:list_dir_all("../test-data/"),
  io:format("get ~p",[File_List]),
  {html,rfc4627:encode(
                  lists:map(fun(File) ->
                              list_to_binary(File)
                            end,
                            File_List)
                )}.
do(File,"html") ->
	io:format("do injectpcap~n"),
	do(string:concat("../test-data/",File)),
	{websocket,web_push,[
						{origin,any},
						{keepalive,true}
						]
	}.
do(Fn) ->
	io:format("open file ~s~n",[Fn]),
	pcapreader:start(Fn,fun reader_cb/1).

reader_cb({eof,Loc,Sta}) ->
	io:format("end of pcap file. ~w Bytes have been parsed ~w Packets handled~n",[Loc,Sta#frame_info.counter]),
	Sta;

reader_cb({verified,{V_Maj,V_Min},{}}) ->
	error_logger:info_msg("pcap verfied, version ~w.~w ~n",[V_Maj,V_Min]),
	#frame_info{version = {V_Maj,V_Min}};

reader_cb({parsed_header,{_Timer_Set,Snap_Length,NI_Type},Sta}) ->
	io:format("header parsed, length:~w NI:~w~n",[Snap_Length,NI_Type]),
	Sta#frame_info{interface = NI_Type,counter = 0};

reader_cb({packet_comming,Packet_Tuple,Sta}) ->
	case Sta#frame_info.interface of
	1 ->
		packet_dispatch:do(l2_packet,Packet_Tuple);
	101 ->
		packet_dispatch:do(ip_packet,Packet_Tuple)
	end,
  NewCounter = Sta#frame_info.counter + 1,
	Sta#frame_info{counter = NewCounter}.


